<template>
  <el-form ref="skuForm" label-width="80px" :rules="rules" class="my-sku-form" :model="skuInfo">
    <el-form-item label="SPU名称">
      <span>{{ spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input
        v-model="skuInfo.skuName"
        placeholder="请输入SKU名称"
      />
    </el-form-item>
    <el-form-item label="价格" prop="price">
      <el-input-number
        v-model="skuInfo.price"
        style="width: 100%"
        controls-position="right"
        :min="0"
      />
    </el-form-item>
    <el-form-item label="重量" prop="weight">
      <el-input-number
        v-model="skuInfo.weight"
        style="width: 100%"
        controls-position="right"
        :min="0"
      />
    </el-form-item>
    <el-form-item label="SKU描述" prop="skuDesc">
      <el-input
        v-model="skuInfo.skuDesc"
        type="textarea"
        placeholder="请输入SKU描述"
      />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row>
        <el-col v-for="(attr,index) in attrList" :key="attr.id" :md="8" :sm="12" :xs="24" class="el-sku-col">
          <el-form-item :label="attr.attrName">
            <el-select v-model="skuInfo.skuAttrValueList[index]">
              <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id" :label="attrValue.valueName" :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`">{{ attrValue.valueName }}</el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>

    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row>
        <el-col v-for="(spuSaleAttr,index) in spuSaleAttrList" :key="spuSaleAttr.id" :md="8" :sm="12" :xs="24" class="el-sku-col">
          <el-form-item :label="spuSaleAttr.saleAttrName">
            <el-select v-model="skuInfo.skuSaleAttrValueList[index]">
              <el-option v-for="saleAttr in spuSaleAttr.spuSaleAttrValueList" :key="saleAttr.id" :label="saleAttr.saleAttrValueName" :value="`${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${saleAttr.id}:${saleAttr.saleAttrValueName}`">{{ saleAttr.saleAttrValueName }}</el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>

    <el-form-item label="图片列表" prop="skuImageList">
      <el-table
        ref="multipleTable"
        border
        tooltip-effect="dark"
        style="width: 100%"
        :data="spuImageList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="图片" align="center">
          <template v-slot="{row}">
            <img :src="row.imgUrl" :alt="row.imgName" style="width:100px;height:100px;">
          </template>
        </el-table-column>
        <el-table-column prop="imgName" label="名称" />
        <el-table-column prop="address" label="操作" show-overflow-tooltip>
          <template v-slot="{row}">
            <el-button v-if="row.isDefault === '0'" type="primary" @click="setDefault(row)">设置默认图片</el-button>
            <el-button v-else type="success" disabled>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">确定</el-button>
      <el-button @click="$emit('update:visible', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from '@/api/product/spu'
import { reqGetAttrList } from '@/api/product/attr'
import { reqSaveSkuInfo } from '@/api/product/sku'
import { mapState } from 'vuex'
export default {
  name: 'SaveSku',
  data() {
    const skuImageListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请至少选择一张图片')
      }
      callback()
    }
    const skuAttrValueListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择一个平台属性')
      }
      callback()
    }
    const skuSaleAttrValueListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择一个销售属性')
      }
      callback()
    }
    return {
      num: 1,
      spuImageList: [], // 图片列表
      spuSaleAttrList: [], // 销售属性及详细属性值列表
      attrList: [], // 平台属性列表
      skuInfo: {
        skuName: '', // SKU名称
        skuDefaultImg: '', // 默认图片
        skuDesc: '', // sku描述
        price: 0, // 价格
        weight: '', // 重量
        skuImageList: [], // 所选图片的集合
        skuAttrValueList: [], // 平台属性
        skuSaleAttrValueList: [] // 销售属性
      },
      rules: {
        skuName: [{ required: true, message: '请输入SKU名称', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
        skuDesc: [{ required: true, message: '请输入SKU描述', trigger: 'blur' }],
        skuImageList: [{ required: true, validator: skuImageListValidate, trigger: 'change' }],
        skuAttrValueList: [{ required: true, validator: skuAttrValueListValidate, trigger: 'change' }],
        skuSaleAttrValueList: [{ required: true, validator: skuSaleAttrValueListValidate, trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id']),
    ...mapState('spu', ['spuId', 'spuName'])
  },
  async mounted() {
    const { category1Id, category2Id, category3Id } = this
    const [responseAttList, responseSpuSaleAttrList, responseSpuImageList] =
      await Promise.allSettled([
        reqGetAttrList(category1Id, category2Id, category3Id),
        reqGetSpuSaleAttrList(this.spuId),
        reqGetSpuImageList(this.spuId)
      ])
    if (responseAttList.status === 'fulfilled') {
      this.attrList = responseAttList.value.data
    }
    if (responseAttList.status === 'fulfilled') {
      this.spuImageList = responseSpuImageList.value.data.map(item => {
        return {
          ...item,
          isDefault: '0'
        }
      })
    }
    if (responseAttList.status === 'fulfilled') {
      this.spuSaleAttrList = responseSpuSaleAttrList.value.data
    }
  },
  methods: {
    // 设置默认图片
    setDefault(row) {
      this.spuImageList.forEach(item => {
        item.isDefault = '0'
      })
      row.isDefault = '1'
      // 保存一下默认图片地址
      this.skuInfo.skuDefaultImg = row.imgUrl
    },
    // 收集所选图片
    handleSelectionChange(val) {
      this.skuInfo.skuImageList = val
    },
    // 添加sku
    submitForm() {
      this.$refs['skuForm'].validate(async(valid) => {
        if (valid) {
          if (!this.skuInfo.skuDefaultImg) { return this.$message.error('请设置默认图片') }
          const {
            skuName,
            price,
            skuDesc,
            weight,
            skuDefaultImg,
            skuImageList,
            skuAttrValueList,
            skuSaleAttrValueList
          } = this.skuInfo
          const res = await reqSaveSkuInfo({
            spuId: this.spuId,
            category3Id: this.category3Id,
            skuName,
            price,
            skuDesc,
            weight,
            skuDefaultImg,
            skuImageList,
            skuAttrValueList: skuAttrValueList.filter(Boolean).map(item => {
              const [attrId, attrName, valueId, valueName] = item.split(':')
              return { attrId, attrName, valueId, valueName }
            }),
            skuSaleAttrValueList: skuSaleAttrValueList.filter(Boolean).map(item => {
              const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(':')
              return { saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName }
            })
          })
          if (res.code === 200) {
            this.$message.success('添加sku成功...')
            this.$emit('update:visible', 1)
          } else {
            this.$message({
              type: 'error',
              message: '添加sku失败...'
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
